from flask import Flask, render_template, send_from_directory, request, redirect, url_for, session, make_response, jsonify
import os
import uuid
from search_api import app as api_app
import datetime

app = Flask(__name__, static_folder='static')
app.secret_key = os.environ.get('SECRET_KEY', 'nankai_search_default_key')

# 确保目录存在
os.makedirs('static', exist_ok=True)
os.makedirs('templates', exist_ok=True)
os.makedirs('data/snapshots', exist_ok=True)
os.makedirs('query_logs', exist_ok=True)

# 用户数据存储
USERS_FILE = 'data/users.json'
if not os.path.exists('data'):
    os.makedirs('data', exist_ok=True)
    
# 初始化用户文件
if not os.path.exists(USERS_FILE):
    import json
    with open(USERS_FILE, 'w', encoding='utf-8') as f:
        json.dump([], f)

# 注册API蓝图
app.register_blueprint(api_app, url_prefix='')

@app.route('/')
def index():
    """渲染搜索主页"""
    # 确保用户有会话ID
    resp = make_response(render_template('index.html'))
    if 'session_id' not in request.cookies:
        session_id = str(uuid.uuid4())
        resp.set_cookie('session_id', session_id, max_age=60*60*24*30)  # 30天过期
    return resp

@app.route('/documents/<path:filename>')
def serve_document(filename):
    """提供文档下载服务"""
    return send_from_directory('crawler/data/documents', filename)

@app.route('/view/document/<doc_id>')
def view_document(doc_id):
    """在线查看文档页面"""
    try:
        from elasticsearch import Elasticsearch
        es = Elasticsearch(["http://localhost:9200"])
        
        # 查询文档信息
        query = {
            "query": {
                "term": {
                    "_id": doc_id
                }
            }
        }
        
        response = es.search(index="nankai_documents", body=query)
        
        if response["hits"]["total"]["value"] == 0:
            return "文档不存在", 404
        
        document = response["hits"]["hits"][0]["_source"]
        file_path = document.get("file_path", "")
        file_name = os.path.basename(file_path) if file_path else ""
        file_type = document.get("file_type", "").lower()
        title = document.get("title", "未知文档")
        
        if not file_name:
            return "文档路径不可用", 404
        
        # 构建文档URL
        doc_url = f"/documents/{file_name}"
        
        return render_template(
            'document_viewer.html',
            doc_id=doc_id,
            title=title,
            file_type=file_type,
            file_name=file_name,
            doc_url=doc_url
        )
    except Exception as e:
        return f"查看文档失败: {str(e)}", 500

@app.route('/snapshot/<page_hash>')
def snapshot(page_hash):
    """显示网页快照"""
    # 直接重定向到API
    return redirect(url_for('search_api.page_snapshot', page_hash=page_hash))

@app.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录页面和处理"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        # 验证用户
        user = authenticate_user(username, password)
        if user:
            session['user_id'] = user['id']
            session['username'] = user['username']
            return redirect('/')
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册页面和处理"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email', '')
        
        # 检查用户是否已存在
        if user_exists(username):
            return render_template('register.html', error='用户名已存在')
        
        # 注册用户
        if register_user(username, password, email):
            return redirect('/login')
        else:
            return render_template('register.html', error='注册失败，请重试')
    
    return render_template('register.html')

@app.route('/logout')
def logout():
    """用户登出"""
    session.pop('user_id', None)
    session.pop('username', None)
    return redirect('/')

@app.route('/user/profile')
def profile():
    """用户个人资料页面"""
    if 'user_id' not in session:
        return redirect('/login')
    
    user_id = session['user_id']
    username = session['username']
    
    # 获取用户查询历史
    import json
    history = []
    log_file = os.path.join('query_logs', f"{user_id}.json")
    if os.path.exists(log_file):
        try:
            with open(log_file, 'r', encoding='utf-8') as f:
                history = json.load(f)
        except:
            pass
    
    return render_template('profile.html', username=username, history=history)

def authenticate_user(username, password):
    """验证用户凭据"""
    import json
    import hashlib
    
    try:
        with open(USERS_FILE, 'r', encoding='utf-8') as f:
            users = json.load(f)
        
        # 查找用户
        for user in users:
            if user['username'] == username:
                # 哈希密码比较
                hashed_password = hashlib.sha256(password.encode()).hexdigest()
                if user['password'] == hashed_password:
                    return user
    except Exception as e:
        print(f"认证错误: {e}")
    
    return None

def user_exists(username):
    """检查用户名是否已存在"""
    import json
    
    try:
        with open(USERS_FILE, 'r', encoding='utf-8') as f:
            users = json.load(f)
        
        for user in users:
            if user['username'] == username:
                return True
    except Exception as e:
        print(f"检查用户存在错误: {e}")
    
    return False

def register_user(username, password, email=''):
    """注册新用户"""
    import json
    import hashlib
    import uuid
    
    try:
        with open(USERS_FILE, 'r', encoding='utf-8') as f:
            users = json.load(f)
        
        # 创建新用户
        user_id = str(uuid.uuid4())
        hashed_password = hashlib.sha256(password.encode()).hexdigest()
        
        new_user = {
            'id': user_id,
            'username': username,
            'password': hashed_password,
            'email': email,
            'created_at': str(datetime.datetime.now())
        }
        
        users.append(new_user)
        
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(users, f, ensure_ascii=False, indent=2)
        
        return True
    except Exception as e:
        print(f"注册用户错误: {e}")
    
    return False

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5000) 